package main

import (
	"bufio"
	"fmt"
	"image"
	"io/ioutil"
	"path/filepath"

	"image/jpeg"
	"image/png"
	"log"
	"os"

	"golang.org/x/image/bmp"
	"golang.org/x/image/draw"
)

func main() {
	//thumbnail
	walkDir("./picture")
}

func walkDir(path string) {
	dirList, err := ioutil.ReadDir(path)
	if err != nil {
		fmt.Println("1")
	}
	for _, v := range dirList {
		p := path + "/" + v.Name()
		if v.IsDir() {
			createFolder(filepath.Clean("./Thumbnail/" + p))
			walkDir(p)
		} else {
			opImg(p)
		}
	}
}
func opImg(path string) {
	f := openFile(path)
	defer f.Close()
	// outpath := filepath.Clean("./Thumbnail/" + f.Name())

	bRf := bufio.NewReader(f)
	bRfP, _ := bRf.Peek(1)
	i := bRfP[0]
	var err error
	var img image.Image
	switch i {
	case 0xFF:
		// fmt.Println("jpg")
		img, err = jpeg.Decode(bRf)
	case 0x89:
		// fmt.Println("png")
		img, err = png.Decode(bRf)
	case 0x42:
		// fmt.Println("bmp")
		img, err = bmp.Decode(bRf)
	}
	if err != nil {
		log.Fatal(err)
	}
	/*取图片中某一点的颜色
	col := img.At(100, 100)
	r, g, b, a := col.RGBA()
	println(r, g, b, a)
	println(r>>8, g>>8, b>>8, a>>8) //源码是 <<8
	*/
	outpath := filepath.Clean("./Thumbnail/" + f.Name())
	fmt.Println("[创建文件] ", outpath)
	fDst := createFlie(outpath)
	defer fDst.Close()
	bounds := img.Bounds()
	dx := bounds.Dx()
	dy := bounds.Dy()
	newdx := 150
	dst := image.NewRGBA(image.Rect(0, 0, newdx, newdx*dy/dx))
	draw.CatmullRom.Scale(dst, image.Rect(0, 0, newdx, newdx*dy/dx), img, bounds, draw.Over, nil)

	switch 1 {
	case 1:
		draw.ApproxBiLinear.Scale(dst, image.Rect(0, 0, newdx, newdx*dy/dx), img, bounds, draw.Over, nil)
	case 2:
		draw.CatmullRom.Scale(dst, image.Rect(0, 0, newdx, newdx*dy/dx), img, bounds, draw.Over, nil)
	case 3:
		draw.NearestNeighbor.Scale(dst, image.Rect(0, 0, newdx, newdx*dy/dx), img, bounds, draw.Over, nil)
	}

	switch i {
	case 0xFF:
		err = jpeg.Encode(fDst, dst, &jpeg.Options{Quality: 100}) //&jpeg.Options{100}图像质量为100
	case 0x89:
		err = png.Encode(fDst, dst)
	case 0x42:
		err = bmp.Encode(fDst, dst)
	}

	if err != nil {
		log.Fatal(err)
	}
}

func openFile(path string) *os.File {
	f, osErr := os.Open(path)
	// fs.file = fSrc
	if osErr == nil {
		return f
	}
	log.Fatal(osErr)
	return nil
}

func createFlie(path string) *os.File {
	fDst, err := os.Create(path)
	if err == nil {
		return fDst
	}
	log.Fatal(err)
	return nil
}

func createFolder(path string) {
	// d := filepath.Dir(path)
	_, err := os.Stat(path)
	if err != nil {
		os.MkdirAll(path, 0777)
		fmt.Println("[创建目录] ", path)
	}

}
